package domain.model.project.support.serializer;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import domain.model.project.Project;
import domain.model.project.ProjectSCM;
import domain.model.project.ProjectType;
import domain.model.project.support.ProjectBuilder;
import util.jackson.serializer.JacksonReader;

import java.io.IOException;

/**
 * @author Gregory Boissinot
 */
public class ProjectDeserializer extends JsonDeserializer<Project> {

    private final JacksonReader jacksonReader;

    public ProjectDeserializer() {
        this.jacksonReader = new JacksonReader();
    }

    @Override
    public Project deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        JsonNode rootNode = jsonParser.getCodec().readTree(jsonParser);

        //-- Required elements
        String org = jacksonReader.readRequiredFieldValue(rootNode, "org", String.class);
        String name = jacksonReader.readRequiredFieldValue(rootNode, "name", String.class);
        String status = jacksonReader.readRequiredFieldValue(rootNode, "status", String.class);

        //-- Optional elements
        String description = jacksonReader.readOptionalField(rootNode, "description", String.class);
        ProjectSCM projectSCM = jacksonReader.readOptionalField(rootNode, "scm", ProjectSCM.class);
        String type = jacksonReader.readOptionalField(rootNode, "type", String.class);
        ProjectType projectType = jacksonReader.readOptionalField(rootNode, type, ProjectType.class);

        ProjectBuilder projectBuilder = new ProjectBuilder(org, name, status);
        projectBuilder.projectSCM(projectSCM).projectType(projectType).description(description);
        return projectBuilder.build();
    }
}
